﻿using CRM.Api.Common;
using CRM.Api.Models;
using CRM.Api.Models.AXB;
using CRM.Infrastructure.Entity;
using CRM.Infrastructure.Service;
using CRM.Utility;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;

namespace CRM.Api.Controllers
{
    /// <summary>
    /// 外呼控制器
    /// </summary>
    public class AXBController : BaseApiController
    {
        /// <summary>
        /// 基地址
        /// </summary>
        protected string BaseUrl = ConfigHelper.GetAppSettingValue("AXBBaseUrl");
        /// <summary>
        ///   账号key
        /// </summary>
        protected string appKey = ConfigHelper.GetAppSettingValue("AXBAppKey");
        /// <summary>
        /// 账号密钥
        /// </summary>
        protected string secretkey = ConfigHelper.GetAppSettingValue("AXBSecretkey");
        /// <summary>
        /// 虚拟号
        /// </summary>
        protected string telX = ConfigHelper.GetAppSettingValue("AXBTelX");

        /// <summary>
        /// 绑定APP
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultData<BindTelResult> BindTel(CallModel call)
        {
            //跟进id获取用户和线索电话
            var usr = new UsersService().SingleOrDefault(call.UserID);
            var clue = new CluesService().SingleOrDefault(call.ClueID);
            BindTelModel model = new BindTelModel(usr.Mobile, clue.HisMobile, Guid.NewGuid().ToString("N"))
            {
                telX = telX
            };

            SortedDictionary<string, string> sorted = new SortedDictionary<string, string>
            {
                { "appkey", appKey },  //应用 id
                { "ts", DateTime.Now.ToString("yyyyMMddHHmmssfff") },  //业务时间戳
                { "requestId", model.requestId },  //业务id
                { "telA", model.telA },  //真实号码
                { "telX", model.telX },
                { "telB", model.telB },  //对端号码
                { "calldisplay",model.extra.calldisplay },  //来的显示
                { "subts", model.subts },  //应用id
                { "anucode", model.anucode },  //放音编码
                { "expiration", model.expiration }  //单位：秒， 自绑定时间开始后 expiration 秒自动解绑；0 表示 不限制时间，不会自动解绑
            };
            
            //请求第三方呼叫转移
            RestClient client = new RestClient(string.Format("{0}/v2/axb/{1}", BaseUrl, "mode101"));
            RestRequest request = new RestRequest(Method.POST)
            {
                RequestFormat = DataFormat.Json
            };
            request.AddHeader("appkey", sorted["appkey"]);
            request.AddHeader("ts", sorted["ts"]);
            request.AddHeader("msgdgt", GetMsgDgt(sorted));
            request.AddJsonBody(model);

            var result = client.Execute<BindTelResult>(request);

            //记录调用接口日志
            var log = new CallLog()
            {
                ClueID = call.ClueID,
                CreatedDate = DateTime.Now,
                RequestId = model.requestId,
                ErrorCode = result.Data.code,
                ErrorMsg = result.Data.message,
                UserID = call.UserID,
                UserMobile = usr.Mobile
            };
            if (result.Data.code == "0")
            {
                log.TelX = result.Data.data.telX;
                log.SubID = result.Data.data.subid;
            }
            new CallLogService().Insert(log);

            //返回结果
            return ResultData<BindTelResult>.Success(result.Data);
        }

        /// <summary>
        /// 绑定电话
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultData<BindTelResult> BindTelPC(CallModelPC call)
        {
            if (call.ClueID < 1)
            {
                return ResultData<BindTelResult>.Error("线索ID错误");
            }
            if (call.CompanyID < 1)
            {
                return ResultData<BindTelResult>.Error("公司CompanyID错误");
            }
            if (string.IsNullOrEmpty(call.Mobile))
            {
                return ResultData<BindTelResult>.Error("电话号码为空");
            }

            //跟进id获取用户和线索电话
            var clue = new CluesService().SingleOrDefault(call.ClueID);
            if (clue.CompanyID != call.CompanyID)
            {
                return ResultData<BindTelResult>.Error("公司和线索不匹配，错误3次将IP加入黑名单");
            }

            BindTelModel model = new BindTelModel(call.Mobile, clue.HisMobile, Guid.NewGuid().ToString("N"))
            {
                telX = telX
            };

            SortedDictionary<string, string> sorted = new SortedDictionary<string, string>
            {
                { "appkey", appKey },  //应用 id
                { "ts", DateTime.Now.ToString("yyyyMMddHHmmssfff") },  //业务时间戳
                { "requestId", model.requestId },  //业务id
                { "telA", model.telA },  //真实号码
                { "telX", model.telX },
                { "telB", model.telB },  //对端号码
                { "calldisplay",model.extra.calldisplay },  //来的显示
                { "subts", model.subts },  //应用id
                { "anucode", model.anucode },  //放音编码
                { "expiration", model.expiration }  //单位：秒， 自绑定时间开始后 expiration 秒自动解绑；0 表示 不限制时间，不会自动解绑
            };


            //请求第三方呼叫转移
            RestClient client = new RestClient(string.Format("{0}/v2/axb/{1}", BaseUrl, "mode101"));
            RestRequest request = new RestRequest(Method.POST)
            {
                RequestFormat = DataFormat.Json
            };
            request.AddHeader("appkey", sorted["appkey"]);
            request.AddHeader("ts", sorted["ts"]);
            request.AddHeader("msgdgt", GetMsgDgt(sorted));
            request.AddJsonBody(model);
            var result = client.Execute<BindTelResult>(request);

            //记录调用接口日志
            var log = new CallLog()
            {
                ClueID = call.ClueID,
                CreatedDate = DateTime.Now,
                RequestId = model.requestId,
                ErrorCode = result.Data.code,
                ErrorMsg = result.Data.message,
                CompanyID = call.CompanyID,
                UserMobile = call.Mobile
            };
            if (result.Data.code == "0")
            {
                log.TelX = result.Data.data.telX;
                log.SubID = result.Data.data.subid;
            }
            new CallLogService().Insert(log);

            //返回结果
            return ResultData<BindTelResult>.Success(result.Data);
        }

        /// <summary>
        /// 同步呼叫记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [Route("v2/axb/callin")]
        public SyncMobile SyncCall(SyncTelModel model)
        {
            new AxbCallLogService().Insert(new AxbCallLog()
            {
                CallDisplay = model.calldisplay,
                CallID = model.callid,
                CallTime = model.calltime,
                CallType = model.calltype,
                RecordMode = model.recordMode,
                RecordUrl = model.recordUrl,
                RedirReason = model.redirreason,
                ReleaseCause = model.releasecause,
                Releasedir = model.releasedir,
                ReleaseTime = model.releasetime,
                RequestId = model.requestId,
                RingingTime = model.ringingtime,
                StartTime = model.starttime,
                SubID = model.subid,
                TelA = model.telA,
                TelB = model.telB,
                TelC = model.telC,
                Telredir = model.telredir,
                TelX = model.telX
            });
            return new SyncMobile()
            {
                message = "SUCCESS",
                code = "0"
            };
        }
        
        /// <summary>
        /// 获取签名
        /// </summary>
        /// <param name="sorted"></param>
        /// <returns></returns>
        private string GetMsgDgt(SortedDictionary<string, string> sorted)
        {
            StringBuilder sb = new StringBuilder(secretkey);
            foreach (var kvp in sorted)
            {
                sb.Append(kvp.Key + kvp.Value);
            }
            return MD5Helper.MD5String(sb.ToString()).ToUpper();
        }
    }
}
